package com.supor.aiot.common.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.baseconfig.common.helper.NetObserverManager;
import com.android.baseconfig.common.observer.NetConnectionObserver;
import com.android.baseconfig.common.utils.DialogUtils;
import com.android.baseconfig.common.utils.Logc;
import com.supor.aiot.common.R;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.databinding.FragmentBaseBinding;
import com.supor.aiot.common.utils.ClassUtil;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.ViewModelProvider;
import butterknife.ButterKnife;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;


public abstract class BaseMVVMFragment<VM extends AndroidViewModel, SV extends ViewDataBinding>
        extends Fragment implements NetConnectionObserver {

    // ViewModel
    protected VM viewModel;
    // 布局view
    protected SV bindingView;
    // fragment是否显示了
    protected boolean mIsVisible = false;
    protected boolean isLoaded = false;
    // 加载中
    private View loadingView;
    // 加载失败
    private View errorView;
    // 空布局
    private View emptyView;
    protected FragmentBaseBinding mBaseBinding;
    private CompositeDisposable mCompositeDisposable;

    protected Activity activity;
    private Dialog dialog;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (Activity) context;
        NetObserverManager.getInstance().addNetObserver(this);
        Logc.i("onAttach: activity: " + activity);
    }

    @Override
    public void onResume() {
        super.onResume();
        //增加了Fragment是否可见的判断
        if (!isLoaded && !isHidden()) {
            loadData();
            Logc.d(this.getClass().getSimpleName() + " lazyInit");
            isLoaded = true;
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Class<SV> svClass = ClassUtil.getViewBinding(this);
        if (svClass != null) {
            mBaseBinding = DataBindingUtil.inflate(activity.getLayoutInflater(),
                    R.layout.fragment_base,
                    null, false);
            bindingView = DataBindingUtil.inflate(activity.getLayoutInflater(), setContent(),
                    null, false);

            // content
            RelativeLayout.LayoutParams params =
                    new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT);
            bindingView.getRoot().setLayoutParams(params);
            RelativeLayout mContainer =
                    (RelativeLayout) mBaseBinding.getRoot().findViewById(R.id.container);
            mContainer.addView(bindingView.getRoot());
            bindingView.setLifecycleOwner(this);
            initEvent();
            return mBaseBinding.getRoot();
        } else {
            View view = inflater.inflate(setContent(), container, false);
            if (view == null) {
                throw new IllegalArgumentException("Fragment should implement initView method and" +
                        " cannot return null");
            }
            ButterKnife.bind(this, view);
            initEvent();
            return view;
        }
    }

    /**
     * 在这里实现Fragment数据的缓加载.
     */
    // @Override
    // public void setUserVisibleHint(boolean isVisibleToUser) {
    //     super.setUserVisibleHint(isVisibleToUser);
    //     if (getUserVisibleHint()) {
    //         mIsVisible = true;
    //         onVisible();
    //     } else {
    //         mIsVisible = false;
    //         onInvisible();
    //     }
    // }
    protected void initData() {
    }

    protected void initEvent() {
    }

    protected void onInvisible() {
    }

    /**
     * 显示时加载数据,需要这样的使用
     * 注意声明 isPrepared，先初始化
     * 生命周期会先执行 setUserVisibleHint 再执行onActivityCreated
     * 在 onActivityCreated 之后第一次显示加载数据，只加载一次
     */
    protected void loadData() {
    }

    protected void onVisible() {
        loadData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViewModel();
        initData();
    }

    /**
     * 初始化ViewModel
     */
    private void initViewModel() {
        Class<VM> viewModelClass = ClassUtil.getViewModel(this);
        if (viewModelClass != null) {
            this.viewModel = new ViewModelProvider(this,
                    ViewModelProvider.AndroidViewModelFactory.getInstance(AppAgent.getApp())).get(viewModelClass);
            Logc.i("initViewModel: " + viewModel);
        }
    }

    protected <T extends View> T getView(int id) {
        return (T) getView().findViewById(id);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isLoaded = false;
    }

    /**
     * 布局
     */
    public abstract int setContent();

    /**
     * 加载失败后点击后的操作
     */
    protected void onRefresh() {
        int type = AppAgent.getNetworkType();
        if (type == 0 || type == 5) {
            showError();
        } else {
            showContentView();
        }
    }

    /**
     * 显示加载中状态
     */
    protected void pageStartLoading() {
        ViewStub viewStub = getView(R.id.vs_loading);
        if (viewStub != null) {
            loadingView = viewStub.inflate();
        }
        if (loadingView != null && loadingView.getVisibility() != View.VISIBLE) {
            loadingView.setVisibility(View.VISIBLE);
        }
        if (bindingView.getRoot().getVisibility() != View.GONE) {
            bindingView.getRoot().setVisibility(View.GONE);
        }
        if (errorView != null) {
            errorView.setVisibility(View.GONE);
        }
        if (emptyView != null && emptyView.getVisibility() != View.GONE) {
            emptyView.setVisibility(View.GONE);
        }
    }

    /**
     * 加载完成的状态
     */
    protected void showContentView() {
        if (bindingView.getRoot().getVisibility() != View.VISIBLE) {
            bindingView.getRoot().setVisibility(View.VISIBLE);
        }
        if (loadingView != null && loadingView.getVisibility() != View.GONE) {
            loadingView.setVisibility(View.GONE);
        }
        if (errorView != null) {
            errorView.setVisibility(View.GONE);
        }
        if (emptyView != null && emptyView.getVisibility() != View.GONE) {
            emptyView.setVisibility(View.GONE);
        }
    }

    /**
     * 加载失败点击重新加载的状态
     */
    protected void showError() {
        ViewStub viewStub = getView(R.id.vs_error_refresh);
        if (viewStub != null) {
            errorView = viewStub.inflate();
            // 点击加载失败布局
            errorView.findViewById(R.id.cl_root).setOnClickListener(v -> {
                pageStartLoading();
                onRefresh();
            });
        }
        if (errorView != null) {
            errorView.setVisibility(View.VISIBLE);
        }
        if (loadingView != null && loadingView.getVisibility() != View.GONE) {
            loadingView.setVisibility(View.GONE);
        }
        if (bindingView.getRoot().getVisibility() != View.GONE) {
            bindingView.getRoot().setVisibility(View.GONE);
        }
        if (emptyView != null && emptyView.getVisibility() != View.GONE) {
            emptyView.setVisibility(View.GONE);
        }
    }

    protected void showEmptyView(String text) {
        // 需要这样处理，否则二次显示会失败
        ViewStub viewStub = getView(R.id.vs_empty);
        if (viewStub != null) {
            emptyView = viewStub.inflate();
            ((TextView) emptyView.findViewById(R.id.tv_tip_empty)).setText(text);
        }
        if (emptyView != null) {
            emptyView.setVisibility(View.VISIBLE);
        }

        if (loadingView != null && loadingView.getVisibility() != View.GONE) {
            loadingView.setVisibility(View.GONE);
        }
        if (errorView != null) {
            errorView.setVisibility(View.GONE);
        }
        if (bindingView != null && bindingView.getRoot().getVisibility() != View.GONE) {
            bindingView.getRoot().setVisibility(View.GONE);
        }
    }

    public void addSubscription(Disposable disposable) {
        if (this.mCompositeDisposable == null) {
            this.mCompositeDisposable = new CompositeDisposable();
        }
        this.mCompositeDisposable.add(disposable);
    }

    public void showLoading(String tips, boolean isCanCancel) {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }
        dialog = DialogUtils.createLoadingDialog(activity, tips);
        dialog.setCancelable(isCanCancel);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.show();
    }

    public void showLoading() {
        showLoading("", true);
    }

    public void closeLoading() {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /**
     * 可复写处理无网络页面
     *
     * @param type {@link com.android.baseconfig.common.utils.NetWorkUtil}
     */
    @Override
    public void updateNetStatus(int type) {
        if (isVisible()) {
            if (type == 0) {
                showError();
            } else {
                showContentView();
            }
        }
    }

    @Override
    public void updateNFCStatus(int state) {

    }

    @Override
    public void updateWifiStatus(int state) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NetObserverManager.getInstance().removeNetObserver(this);
        if (this.mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
            this.mCompositeDisposable.clear();
        }
    }

    public void removeDisposable() {
        if (this.mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
            this.mCompositeDisposable.dispose();
        }
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        activity.overridePendingTransition(com.android.baseconfig.R.anim.activity_open_enter, com.android.baseconfig.R.anim.activity_open_exit);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        activity.overridePendingTransition(com.android.baseconfig.R.anim.activity_open_enter, com.android.baseconfig.R.anim.activity_open_exit);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
